package useraddress

import (
	"context"
	// "fmt"
	"strings"

	"mall/common/globalkey"
	"mall/common/modelx"
	"mall/common/resultx"
	"mall/common/utils/pointy"
	"mall/service/user/model"
	"mall/service/user/rpc/internal/svc"
	"mall/service/user/rpc/types/user"

	// "github.com/sirupsen/logrus"
	"github.com/zeromicro/go-zero/core/logx"
)

type GetUserAddressByIdLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewGetUserAddressByIdLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetUserAddressByIdLogic {
	return &GetUserAddressByIdLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *GetUserAddressByIdLogic) GetUserAddressById(in *user.BaseIdReq) (*user.UserAddressInfo, error) {
	// logrus.Info(fmt.Sprintf("GetUserAddressById BaseIdReq: %+v", in))
	// Id:11 Preload:"userAddress:Id,Consignee,Mobile,Province,City,District,DetailedAddress,PostalCode,IsDefault,meta" Filter:"UserId,equalTo:10021;Status,equalTo:1" VisitorId:10021 PlatformId:1

	if (in.Filter == nil || len(*in.Filter) == 0) && (in.Id == nil || *in.Id == 0) {
		return nil, resultx.StatusError(resultx.USER_ADDRESS_ID_REQUIRED, "")
	}

	preloadMap, _ := modelx.ParsePreloadAndEagerLoad(in.Preload, in.EagerLoad)
	// logrus.Info(fmt.Sprintf("GetUserAddressById preloadMap: %+v", preloadMap))
	// map[userAddress:[Id Consignee Mobile Province City District DetailedAddress PostalCode IsDefault meta]]

	resp := &user.UserAddressInfo{}

	userAddressEntityName := model.RpcEntityNames.UserAddress
	if _, ok := model.RpcEntityPreloadMap[userAddressEntityName]; !ok {
		return resp, nil
	}

	userAddressRepositoryName := model.RepositoryNames.UserAddress
	columnMap, ok := model.RepositoryPreloadMap[userAddressRepositoryName]
	if !ok {
		return resp, nil
	}

	var address *model.UserAddress
	if in.Filter != nil && len(*in.Filter) > 0 {
		var selectCols []string
		if preloadFields, ok := preloadMap[userAddressEntityName]; ok {
			selectCols = modelx.ParseSelectColumns(preloadFields, columnMap)
		}

		filterMap := modelx.ParseFilter(in.Filter, columnMap)
		// logrus.Info(fmt.Sprintf("GetUserAddressById filterMap: %+v", filterMap))
		// map[status:map[equalTo:[1]] user_id:map[equalTo:[10021]]]
		if filterMap == nil {
			return nil, resultx.StatusError(resultx.REUQEST_PARAM_ERROR, "")
		}

		if in.Id != nil && *in.Id > 0 {
			filterMap[model.UserAddressColumns.UserAddressID] = map[string][]any{
				"equalTo": []any{*in.Id},
			}
		}

		orderBy := modelx.ParseSorter(in.Sorter, columnMap)
		// logrus.Info(fmt.Sprintf("GetUserAddressById orderBy: %s", orderBy))
		//
		if len(orderBy) == 0 {
			orderBy = model.UserAddressColumns.LastUsedAt + " DESC, " + model.UserAddressColumns.CreatedAt + " DESC"
		}

		res, _, err := l.svcCtx.UserAddress.GetList(l.ctx, model.M{
			"pageSize": uint64(1),
			"orderBy":  orderBy,
			"select":   strings.Join(selectCols, ","),
		}, -1, filterMap)
		if err != nil {
			return nil, err
		}

		if len(res) == 0 {
			return resp, nil
		}

		address = res[0]
	} else if in.Id != nil && *in.Id > 0 {
		data, err := l.svcCtx.UserAddress.FindOne(l.ctx, *in.Id)
		if err != nil {
			return nil, err
		}

		address = data
	}

	if address == nil {
		return resp, nil
	}

	if address.Status != uint8(globalkey.StatusEnabled) {
		return resp, nil
	}

	if in.VisitorId != nil && *in.VisitorId != address.UserID {
		return resp, nil
	}

	var isDefault uint32
	if address.IsDefault > 0 {
		isDefault = 1
	}
	var geographic []*user.UserMetaInfo
	if address.Geographic.Valid {
		if err := address.Geographic.Unmarshal(&geographic); err != nil {
			logx.Errorw("GetUserAddressById Geographic.Unmarshal err", logx.Field("detail", err.Error()))
		}
	}

	return &user.UserAddressInfo{
		Id:              pointy.GetPointer(address.UserAddressID),
		UserId:          pointy.GetPointer(address.UserID),
		Label:           pointy.GetPointer(address.Label),
		Consignee:       pointy.GetPointer(address.Consignee),
		Mobile:          pointy.GetPointer(address.Mobile),
		Province:        pointy.GetPointer(address.Province),
		City:            pointy.GetPointer(address.City),
		District:        pointy.GetPointer(address.District),
		Street:          pointy.GetPointer(address.Street),
		DetailedAddress: pointy.GetPointer(address.DetailedAddress),
		PostalCode:      pointy.GetPointer(address.PostalCode),
		RegionCode:      pointy.GetPointer(address.RegionCode),
		IsDefault:       pointy.GetPointer(isDefault),
		Status:          pointy.GetPointer(uint32(address.Status)),
		LastUsedAt:      pointy.GetPointer(modelx.FormatNullDotTime(address.LastUsedAt, "")),
		CreatedAt:       pointy.GetPointer(modelx.FormatTime(address.CreatedAt, "")),
		UpdatedAt:       pointy.GetPointer(modelx.FormatTime(address.UpdatedAt, "")),
		DeletedAt:       pointy.GetPointer(modelx.FormatNullDotTime(address.DeletedAt, "")),
		Geographic:      geographic,
	}, nil
}
